#include "SceneBuilder.h"
#include "..\Util\FileUtil.h"

using namespace std;
using namespace util;

SceneBuilder::SceneBuilder(const std::string &sceneFile)
{
	width  = 0;
	height = 0;

	if (FileUtil::fileExists(sceneFile))
	{
		content = FileUtil::fileToString(sceneFile);

		int indexEnd = content.find("</asteroides>");
		content = content.substr(0,indexEnd+13);

		size_t screenWidth = content.find("ancho=");
		if (screenWidth != string::npos)
		{
			screenWidth += 7;
			size_t endWidth = content.find_first_of("\"", screenWidth + 1);
			string widthStr = content.substr(screenWidth, endWidth - screenWidth).c_str();
			width = atoi(widthStr.c_str());
		}

		size_t screenHeight = content.find("alto=");
		if (screenHeight != string::npos)
		{
			screenHeight += 6;
			size_t endHeight = content.find_first_of("\"", screenHeight + 1);
			string heigthStr = content.substr(screenHeight, endHeight - screenHeight).c_str();
			height = atoi(heigthStr.c_str());
		}
	}
}

SceneBuilder::~SceneBuilder()
{
}

int SceneBuilder::getSceneWidth()
{
	return width;
}
int SceneBuilder::getSceneHeight()
{
	return height;
}

void SceneBuilder::replace(const string &str, const string &newstr)
{
	size_t aux = content.find(str);
	while(aux != string::npos)
	{
		size_t start_pos = content.find(str);
		content.replace(start_pos, str.length(), newstr);
		aux = content.find(str);
	}
}

void SceneBuilder::addTag(const string &tag, const string &properties)
{
	string line = string("\n<") + tag + string(" ") + properties + string(" />");
	content.append(line);
}

void SceneBuilder::addLine(const string &line)
{
	content.append(line);
}


string SceneBuilder::toString()
{
	if (content.find("</asteroids>") == string::npos)
		content.append("\n</asteroids>\n");

	return content;
}

void SceneBuilder::saveTo(const string &file)
{
	fstream tempXMLWithShipsFile(file, ios::out);
	tempXMLWithShipsFile.write(content.c_str(), content.length());
	tempXMLWithShipsFile.flush();
	tempXMLWithShipsFile.close();
}
